﻿using System;
using System.IO;
using System.Web;

using BlueCMS.Core;
using BlueCMS.Core.Entities;
using BlueCMS.Core.Services;

namespace BlueCMS.HttpModules.UrlRewrite
{
    public class UrlRewriteModule : IHttpModule
    {
        public void  Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginRequest);
            context.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
            context.AuthenticateRequest += new EventHandler(AuthenticateRequest);
        }

        public void Dispose()
        {

        }

        void AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;

            // Find the user for this request. If we aren't authenticated then use the guest user
            User user = null;
            if (application.Context.User != null && application.Context.User.Identity.IsAuthenticated)
            {
                user = UserService.GetUserForWebsiteByName(CmsApplication.CmsWebsite, application.Context.User.Identity.Name);
            }
            else
            {
                user = UserService.GetGuestUserForWebsite(CmsApplication.CmsWebsite);
            }
            CmsApplication.CmsUser = user;
        }

        void BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;

            // Find the website for this request
            string domain = application.Context.Request.Url.Host.ToLower();
            if (domain.StartsWith("www."))
            {
                domain = domain.Remove(0, 4);
            }

            Website website = WebsiteService.GetWebsiteForDomain(domain);
            if (website == null)
            {
                throw new HttpException("No website configured for this domain");
            }
            CmsApplication.CmsWebsite = website;

            string originalUrl = application.Context.Request.Url.AbsolutePath;

            if (originalUrl.EndsWith("/"))
            {
                originalUrl = String.Format("{0}index.cms", originalUrl);
            }

            CmsApplication.CmsOriginalUrl = originalUrl;

            string filePath = application.Context.Server.MapPath(originalUrl);
            if (File.Exists(filePath))
            {
                return;
            }

            if (originalUrl.EndsWith(".axd"))
            {
                return;
            }

            application.Context.RewritePath("~/Dispatch.ashx", false);
        }

        void PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            application.Context.RewritePath(CmsApplication.CmsOriginalUrl);
        }
    }
}
